package jmu.edu.yjc.service.impl;

import jmu.edu.yjc.Utils.BeanCopyUtil;
import jmu.edu.yjc.Utils.JwtUtil;
import jmu.edu.yjc.Utils.RedisCache;
import jmu.edu.yjc.domain.ResponseResult;
import jmu.edu.yjc.domain.entity.LoginUser;
import jmu.edu.yjc.domain.entity.User;
import jmu.edu.yjc.domain.vo.user.UserInfoVo;
import jmu.edu.yjc.domain.vo.user.UserLoginVo;
import jmu.edu.yjc.service.LoginService;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
@Service
public class LoginServiceImpl implements LoginService {
    @Resource
    private AuthenticationManager authenticationManager;
    @Resource
    private RedisCache redisCache;
    @Override
    public ResponseResult userLogin(User user) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //判断是否认证通过
        if(Objects.isNull(authenticate)){
            return ResponseResult.errorResult(-1,"用户名或密码错误");
        }
        //获取userid生成token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        Long id = loginUser.getUser().getId();
        String jwt = JwtUtil.createJWT(id.toString());
        // 把用户信息存入redis
        redisCache.setCacheObject("csamslogin:"+id,loginUser,48, TimeUnit.HOURS);
        //把token和userinfo封装，返回
        UserInfoVo userInfoVo = BeanCopyUtil.copyBeans(loginUser.getUser(), UserInfoVo.class);
        UserLoginVo blogUserLoginVo = new UserLoginVo(jwt,userInfoVo);
        return ResponseResult.okResult(blogUserLoginVo);
    }

    @Override
    public ResponseResult userLogout() {
        //解析token获取userID
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();

        //获取userID
        Long userID = loginUser.getUser().getId();
        //删除redis中的用户信息
        redisCache.deleteObject("csamslogin:"+userID);
        return ResponseResult.okResult();
    }
}
